<!-- src/views/system/document/index.vue -->
<template>
  <div class="app-container">
    <el-card shadow="never" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>文档管理</span>
        <!-- <el-button style="float: right; margin-top: -5px;" type="primary" @click="handleUpload">
          <i class="el-icon-upload2"></i> 开始上传
        </el-button> -->
       
      <el-upload style="float: right; margin-top: -5px;"
          ref="uploadRef"
          :action="actionUrl"
          :auto-upload="false"
          :http-request="uploadFile"
          :on-change="handleFileChange"
          :on-success="handleUploadSuccess"
          accept=".docx,.doc"
          multiple
        >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button size="small" type="success" @click="handleUpload" v-if="selectedFile">开始上传</el-button>
      </el-upload>
          <!-- 使用计算属性显示文件数量 -->
        <p v-if="uploadFileCount > 0">已选择 {{ uploadFileCount }} 个文件</p>
        
        <!-- 调试信息 -->
        <div class="debug-info" v-if="debugMode">
          <p>事件参数中的fileList长度: {{ eventFileListLength }}</p>
          <p>组件实例中的fileList长度: {{ uploadFileCount }}</p>
        </div>
      </div> 
    </el-card>

    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>文档列表</span>
        <div class="filter-container">
          <el-input v-model="queryParams.fileName" placeholder="请输入文件名" size="small" @keyup.enter.native="handleQuery" style="width: 200px;">
            <el-button slot="append" icon="el-icon-search" @click="handleQuery"></el-button>
          </el-input>
        </div>
      </div>
      
      <el-table
        :data="documentList"
        border
        fit
        highlight-current-row
        stripe
        @row-dblclick="handleEdit"
        style="width: 100%; margin-bottom: 15px;">
        <el-table-column label="文件名" prop="fileName" min-width="200">
          <template slot-scope="scope">
            <el-link :underline="false" @click="handleEdit(scope.row)">{{ scope.row.fileName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" prop="fileSize" min-width="100" :formatter="formatFileSize"></el-table-column>
        <el-table-column label="创建者" prop="createBy" min-width="100"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" min-width="160"></el-table-column>
        <el-table-column label="操作" min-width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { listDocument, uploadDocument, deleteDocument } from '@/api/system/document'
import { download } from '@/utils/request'
import {formatSize} from '@/utils/format'

export default {
  data() {
    return {
      // 文档列表
      documentList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: ''
      },
      // 总记录数
      total: 0,
      actionUrl: "",
      selectedFile: null,   // 当前选择的文件
    }
  },
  created() {
    this.getDocumentList()
  },

  computed: {
    hasFileToUpload() {
      return this.$refs.uploadRef?.fileList.length > 0;
    },
    uploadFileCount() {
      return this.$refs.uploadRef?.fileList.length || 0;
    }
  },

  methods: {
    // 获取文档列表
    getDocumentList() {
      listDocument(this.queryParams).then(response => {
        this.documentList = response.rows
        this.total = response.total
      })
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getDocumentList()
    },
    
    // 处理每页条数变化
    handleSizeChange(size) {
      this.queryParams.pageSize = size
      this.getDocumentList()
    },
    
    // 处理当前页变化
    handleCurrentChange(page) {
      this.queryParams.pageNum = page
      this.getDocumentList()
    },
    


    // 用户点击上传调用
    async handleUpload(){

      if (!this.hasFileToUpload) {
        console.log("fileList:"+ this.$refs.uploadRef?.fileList.length );
        this.$message.success('没有文件要上传');
        return;
      }
        // 触发上传 调用配置 :http-request="uploadFile"
        // 即触发 uploadFile函数
        await this.$refs.uploadRef.submit();
        // 上传完成后执行的操作 ...
    },
    
    uploadFile(param){
      let fd = new FormData();
      fd.append('file',param.file);
       //调用上传接口
      uploadDocument(fd).then(res => {
        this.$message.success('上传成功');
          // this.clearFile();
          // 手动触发成功回调
          this.$refs.uploadRef.handleSuccess(
            res.data,  // 服务器响应数据
            this.selectedFile,  // 当前文件对象
            [this.selectedFile]  // 文件列表
          );
      /*上传成功处理*/
          }).catch(err => {/*报错处理*/});

    },

  //   // 上传成功处理
  //   handleUploadSuccess(response, file, fileList) {
  // // 使用uploadDocument API处理上传
  //       uploadDocument(file.raw).then(res => {
  //         this.$message.success('上传成功');
  //         this.getDocumentList();
  //       }).catch(err => {
  //         this.$message.error('上传失败：' + err.message);
  //       });
  //   },
    
  //   // 上传失败处理
  //   handleUploadError(err, file, fileList) {
  //     this.$message({
  //       message: '上传失败：' + err.message,
  //       type: 'error'
  //     })
  //   },
    
    // 上传前校验
    beforeUpload(file) {
      const isWord = file.type === 'application/msword' || 
                     file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      
      if (!isWord) {
        this.$message.error('请上传Word文档(.docx或.doc)')
        return false
      }
      
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过100MB')
        return false
      }
      
      return true
    },

    // 处理文件选择变化
    handleFileChange(file, fileList) {
      this.selectedFile = file;
      this.eventFileListLength = fileList.length;
      console.log('Selected file:', file);
      // 使用nextTick访问更新后的组件状态
      this.$nextTick(() => {
        console.log('nextTick中的fileList长度:', this.uploadFileCount);
      });
    },

    // 上传成功处理
    handleUploadSuccess(response, file, fileList) {
      this.uploading = false;
      this.$message.success('文件上传成功');
      this.clearFileSelection();  // 上传成功后清除文件选择
      this.$emit('uploadSuccess', response);  // 通知父组件上传成功
    },

    // 清除文件选择
    clearFileSelection() {
      this.$refs.uploadRef.clearFiles();
      this.selectedFile = null;
      this.$nextTick(() => {
        console.log('清除文件: 完成');
        console.log('fileList:', this.$refs.uploadRef?.fileList);
        console.log('hasFileToUpload:', this.hasFileToUpload);
      });
    },
    
    // 处理编辑
    handleEdit(row) {
      this.$router.push({ path: '/system/document/edit/' + row.documentId })
    },
    
    // 处理删除
    handleDelete(row) {
      this.$confirm('确定要删除该文档吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteDocument(row.documentId)
      }).then(() => {
        this.getDocumentList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    
    // 格式化文件大小
    formatFileSize(row, column) {
      return formatSize(row.fileSize)
    }
  }
}
</script>